package com.owlab.dcs;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.logging.Level;
import java.util.logging.Logger;


public class Main {
	private static Logger logger = null;
	private static boolean isTail = false;
	private static int numOfDigits = -1;
	private static int portNumber = 50010;
	private static String nextServerLocation = null;
	private static int nextServerPort = -1;
	private ServerSocket server = null;
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		if(args.length == 1) {
			portNumber = Integer.parseInt(args[0]);
			isTail = true;
			// that is, this is tail server instiation.
		} else if(args.length == 4) {
			numOfDigits = Integer.parseInt(args[0]);
			portNumber = Integer.parseInt(args[1]);
			nextServerLocation = args[2];
			nextServerPort = Integer.parseInt(args[3]);	

		} else {
			System.out.println("Usage: program <number of digits> <listening port> <location of next server> <port of the next server>");
			System.out.println("Or program <listening port number>, if you want to start tail server.");
			System.exit(-1);
		}


		Main com = new Main();
		if(isTail) {
			com.listen4TailServer();
		} else {
			com.listen4ComServer();
		}


	}

	public Main(){
		logger = Logger.getLogger(this.getClass().getName());

		if(isTail) {
			logger.log(Level.INFO, "Start listening on port: " + portNumber);
		} else {
			logger.log(Level.INFO, "Pi calculation: " + numOfDigits);
			logger.log(Level.INFO, "Start listening on port: " + portNumber);
			logger.log(Level.INFO, "Next server location: "+ nextServerLocation);
			logger.log(Level.INFO, "Next server port: " + nextServerPort);
		}
	}

	private void listen4ComServer(){
		try {
			server = new ServerSocket(portNumber);

			logger.log(Level.INFO, "ComServer initialized and listening...");

			while(true){
				ComServer worker = null;


				worker = new ComServer(server.accept(), numOfDigits ,nextServerLocation, nextServerPort);

				Thread t = new Thread(worker);
				t.start();

			}
		}catch(IOException e){
			System.out.println(e);
			System.exit(-1);
		}
	}

	private void listen4TailServer(){
		try {
			server = new ServerSocket(portNumber);

			logger.log(Level.INFO, "TailServer initialized and listening...");

			while(true){
				TailServer worker = null;


				worker = new TailServer(server.accept());

				Thread t = new Thread(worker);
				t.start();

			}
		}catch(IOException e){
			System.out.println(e);
			System.exit(-1);
		}
	}

}
